#include "iblog_in.h"

char		__IBLOG_VERSION_0_1_0[] = "0.1.0" ;
char		*__IBLOG_VERSION = __IBLOG_VERSION_0_1_0 ;

static void version()
{
	printf( "iblog v%s build %s %s\n" , __IBLOG_VERSION , __DATE__ , __TIME__ );
	printf( "Copyright by calvin 2017\n" );
	printf( "Email : calvinwilliams@163.com\n" );
	return;
}

static void usage()
{
	printf( "USAGE : iblog -f iblog.conf -a start\n" );
	
	return;
}

int main( int argc , char *argv[] )
{
	struct IblogEnv		*p_env = NULL ;
	int			i ;
	
	int			nret = 0 ;
	
	if( argc > 1 )
	{
		p_env = (struct IblogEnv *)malloc( sizeof(struct IblogEnv) ) ;
		if( p_env == NULL )
		{
			printf( "malloc failed , errno[%d]\n" , errno );
			return 1;
		}
		memset( p_env , 0x00 , sizeof(struct IblogEnv) );
		
		for( i = 1 ; i < argc ; i++ )
		{
			if( strcmp( argv[i] , "-v" ) == 0 )
			{
				version();
				exit(0);
			}
			else if( strcmp( argv[i] , "-f" ) == 0 && i + 1 < argc )
			{
				p_env->iblog_conf_filename = argv[++i] ;
			}
			else if( strcmp( argv[i] , "-a" ) == 0 && i + 1 < argc )
			{
				p_env->cmd_param._action = argv[++i] ;
			}
			else
			{
				printf( "Invalid opt[%s]\r\n" , argv[i] );
				usage();
				exit(7);
			}
		}
		
		if( p_env->iblog_conf_filename == NULL )
			p_env->iblog_conf_filename = "iblog.conf" ;
		
		memset( p_env->iblog_conf_pathfilename , 0x00 , sizeof(p_env->iblog_conf_pathfilename) );
		snprintf( p_env->iblog_conf_pathfilename , sizeof(p_env->iblog_conf_pathfilename)-1 , "%s/etc/%s" , getenv("HOME") , p_env->iblog_conf_filename );
		
		CreateLogHandleG();
		nret = SetLogOutput2G( LOG_OUTPUT_FILE , NULL , NULL , NULL , NULL , NULL , NULL , "%s/log/iblog.log" , getenv("HOME") ) ;
		if( nret )
		{
			printf( "SetLogOutput2G failed[%d]\n" , nret );
			return 1;
		}
		SetLogLevelG( LOG_LEVEL_DEBUG );
		SetLogStylesG( LOG_STYLE_DATETIME|LOG_STYLE_LOGLEVEL|LOG_STYLE_PID|LOG_STYLE_SOURCE|LOG_STYLE_FORMAT|LOG_STYLE_NEWLINE , NULL );
		
		nret = LoadConfig( p_env ) ;
		if( nret )
		{
			printf( "LoadConfig[%s] failed[%d]\n" , p_env->iblog_conf_pathfilename , nret );
			return 1;
		}
		
		if( p_env->cmd_param._action && STRCMP( p_env->cmd_param._action , == , "start" ) )
		{
			nret = InitEnvironment( p_env ) ;
			if( nret )
			{
				printf( "InitEnvironment failed[%d]\n" , nret );
				return 1;
			}
			
			nret = BindDaemonServer( & _monitor , p_env ) ;
			if( nret < 0 )
			{
				printf( "BindDaemonServer failed[%d]\n" , nret );
				ERRORLOGG( "--- iblog end --- " );
			}
			
			CleanEnvironment( p_env );
		}
		else
		{
			usage();
			exit(7);
		}
		
		free( p_env );
	}
	else
	{
		usage();
		return 7;
	}
	
	return abs(nret);
}

